import json

from django.db import transaction
from django.views import View
from django.http import JsonResponse

from leisurely.utils import get_house_count_date
from six_it.models import Order, House, HouseImage, User, Facility


class AcceptanceRejectionView(View):
    '''接单和拒单视图'''

    def put(self,request, order_id):
        '''接单时确认,拒单说明原因'''
        # 接受参数
        dict = json.loads(request.body)
        action = dict.get('action')
        reason = dict.get('reason')

        # 校验参数
        if not action:
            return JsonResponse({'errno':'4103', 'errmsg':'参数错误'})
        # 校验action参数操作类型
        if action not in ('accept', 'reject'):
            return JsonResponse({'errno':'4103', 'errmsg':'参数错误'})


        # 链接数据库
        try:
            order = Order.objects.get(id=order_id, status=0)
            house = order.house
        except Exception as e:
            print(e)
            return JsonResponse({'errno':'4001', 'errmsg':'数据库查询错误'})
        # 房东接属于自己的订单
        if not order or house.user.id != request.user.id:
            return JsonResponse({'errno':'4004', 'errmsg':'数据错误'})

        try:
            # 接单,修改订单状态
            if action =='accept':
                count = get_house_count_date(house,str(order.begin_date),str(order.end_date))
                if count == 0:
                    return JsonResponse({'errno':'4004', 'errmsg':'房屋不足'})
                    # 显式的开启一个事务
                with transaction.atomic():
                    # 创建事务保存点
                    save_id = transaction.savepoint()

                    order.status = 3
                    order.save()

                    # 增加房屋订单数
                    house.order_count += 1
                    house.save()

                    # 清除保存点
                    transaction.savepoint_commit(save_id)

            # 拒单,修改订单状态，填写原因
            else:
                if not reason:
                    return JsonResponse({'errno': '4103', 'errmsg': '参数错误'})

                order.status=6
                order.comment=reason
                order.save()
        except Exception as e:
            print(e)
            return JsonResponse({ "errno": "4004","errmsg": "数据错误"})

        # 返回
        return JsonResponse({ "errno": "0","errmsg": "操作成功"})


class CommentOrdersView(View):
    '''评论订单'''

    def put(self, request, order_id):
        '''房东接单后,房客订单状态显示待评价'''
        # 接受参数
        dict = json.loads(request.body)
        comment = dict.get('comment')

        # 校验参数
        if not comment:
            return JsonResponse({'errno': '4103', 'errmsg': '参数错误'})
        # 链接数据库
        try:
            order = Order.objects.get(id=order_id, status=3)
            house = order.house
        except Exception as e:
            return JsonResponse({'errno':'4001', 'errmsg':'数据库查询错误'})

        # 判断order的信息
        if order is None:
            return JsonResponse({'errno': '4004', 'errmsg': '数据错误'})

        # # 显式的开启一个事务
        # with transaction.atomic():
        #     # 创建事务保存点
        #     save_id = transaction.savepoint()

            # 修改订单状态,保存评论信息
        order.status=4
        order.comment=comment
        order.save()

        # 返回
        return JsonResponse({"errno": '0', "errmsg": "评论成功"})



class HouseRecommendationView(View):
    '''首页房屋推荐'''

    def get(self, request):
        # 链接数据库获取房屋信息
        try:
            houses = House.objects.all().order_by('-create_time')[:5]
        except Exception as e:
            return JsonResponse({'errno': '4001', 'errmsg': '数据库查询错误'})

        data=[]

        # 遍历
        for house in houses:
            data.append({
                "house_id": house.id,
                "img_url": house.index_image_url,
                "title": house.title
            })
        # 返回
        return JsonResponse({ "errno": "0", "errmsg": "OK", "data":data})















